package com.eagledata.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;



/**
 * @author XM
 * 
 *
 */
public class HttpsUtils {
	
	/**
	 * 忽视证书HostName
	 */
	private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
		public boolean verify(String s, SSLSession sslsession) {
			System.out.println("WARNING: Hostname is not matched for cert.");
			return true;
		}
	};
	
	private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {

		private X509Certificate[] certificates;

		@Override
		public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException {
			if (this.certificates == null) {
				this.certificates = certificates;
				System.out.println("init at checkClientTrusted");
			}

		}

		@Override
		public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
			if (this.certificates == null) {
				this.certificates = ax509certificate;
				System.out.println("init at checkServerTrusted");
			}
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};
	
	
	
	
	
	/**
	 *
	 * @Description		:  忽略证书的GET请求
	 * @author    		:  XueMeng
	 * @date      		:  2018年6月27日 下午4:18:57
	 * @return    		:  String
	 * @参数说明	  		:  @param urlString
	 * @参数说明	  		:  @return
	 *
	 */
	public static String doGetByHttps(String urlString) {
		String repString="";
		try {
			
			urlString = new String(urlString.getBytes("ISO8859-1"));
			URL url = new URL(urlString);
			HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
			
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setRequestMethod("GET");
			// connection.setRequestProperty(key, value)

			// Prepare SSL Context
			TrustManager[] tm = { ignoreCertificationTrustManger };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());

			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			connection.setSSLSocketFactory(ssf);
			
			InputStream reader = connection.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(reader, "utf8"));  
			
			StringBuffer buffer = new StringBuffer(); 
			String line = "";  
			while ((line = in.readLine()) != null){  
				 buffer.append(line); 
				 buffer.append("\r\n");
			}
			repString = buffer.toString(); 
			reader.close();
			in.close();
			connection.disconnect();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			
		}
		return repString;
	}
	
	
	/**
	 *
	 * @Description		:  忽略证书的请求
	 * @author    		:  XueMeng
	 * @date      		:  2017年12月6日 下午4:56:41
	 * @return    		:  String
	 * @参数说明	  		:  @return
	 *
	 */
	public static String doPostByHttps(String url, String reqBody) {
		String result = "";
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		configureHttpClient2(httpClientBuilder);
		CloseableHttpClient httpClient = httpClientBuilder.build();
		HttpPost post = new HttpPost();
		HttpEntity entity = new StringEntity(reqBody, ContentType.APPLICATION_JSON);
		post.setEntity(entity);
		try {
			post.setURI(new URI(url));
			CloseableHttpResponse resp = httpClient.execute(post);
			HttpEntity httpEntity = resp.getEntity();
			result = EntityUtils.toString(httpEntity);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static void configureHttpClient2(HttpClientBuilder clientBuilder) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);

			clientBuilder.setSSLContext(ctx);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
